/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.hpi.generationmanager.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 *
 * @author igor_c
 */
public class CSVTable {

    private static final int BUFFER_SIZE_IN_BYTES = 100000;
    private File aDataFile = null;
    BufferedReader aTableReader = null;

    public CSVTable(File aDataFile) {
        this.aDataFile = aDataFile;
    }

    public static ArrayList<CSVTable> findTables(String aContainerFolder) throws Exception {
        ArrayList<CSVTable> result = new ArrayList<CSVTable>();
        File aCSVsFolder = new File(aContainerFolder);
        validateFolder(aCSVsFolder);

        for (File file : aCSVsFolder.listFiles()) {
            if (file.getName().endsWith(".csv")) {
                result.add(new CSVTable(file));
            }
        }

        return result;
    }

    private static void validateFolder(File aCSVsFolder) throws FileNotFoundException {
        if (!aCSVsFolder.exists() && !aCSVsFolder.isDirectory()) {
            throw new FileNotFoundException(String.format("Folder [%s] was not found.", aCSVsFolder.getAbsolutePath()));
        }
    }

    public long length() {
        return aDataFile.length();
    }

    public String getName() {
        return aDataFile.getName();
    }

    public void openForRead() throws Exception {
        aTableReader = new BufferedReader(new FileReader(aDataFile), BUFFER_SIZE_IN_BYTES);
    }

    public ArrayList<Integer> readNextRowDataAsIntegers() throws Exception {
       ArrayList<String> aCellDataAsStrings = readNextRowDataAsStrings();
        ArrayList<Integer> result = null;

        if (aCellDataAsStrings != null) {
            result = new ArrayList<Integer>(aCellDataAsStrings.size());
            for (String aCellDataAsString : aCellDataAsStrings) {
                result.add(Integer.parseInt(aCellDataAsString));
            }
        }

        return result;
    }

    public ArrayList<String> readNextRowDataAsStrings() throws Exception {
      ArrayList<String> result = null;

        String aRowString = aTableReader.readLine();
        if (aRowString != null) {
            String[] aCellDatas = aRowString.split(",");
            result = new ArrayList<String>(aCellDatas.length);
            result.addAll(Arrays.asList(aCellDatas));
        }
        return result;
    }

    public void closeAfterRead() throws Exception {
        aTableReader.close();
        aTableReader = null;
    }

    public boolean  isOpen() throws Exception {
        return (aTableReader != null);
    }

    public ArrayList<String> readHeader() throws Exception {
        return readNextRowDataAsStrings();
    }
}
